import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import { queryCompanies } from '@/pages/SystemUser/service';
import { Auths, Role } from '@/utils/types.d';
import { ModalForm } from '@ant-design/pro-components';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Image } from 'antd';
import { useRef, useState } from 'react';
import { useModel } from 'umi';
import { queryParkinglotNames } from '../Spot/service';
import HandleReport from './components/HandleReport';
import { queryFailureReportList } from './service';
import type { FailureReportTableItem } from './types.d';

const FailureReportList = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const auths = currUser?.auth ? new Set(currUser.auth.failureReport || []) : new Set();
  const ifModify = auths.has(Auths.MODIFY);

  const [imgModalVisible, setImgModalVisible] = useState<boolean>(false);
  const [imgUrl, setImgUrl] = useState<string>('');

  const [upVisible, setUpVisible] = useState<boolean>(false);
  const [currId, setCurrId] = useState<string>('');

  const actionRef = useRef<ActionType>();

  const columns: ProColumns<FailureReportTableItem>[] = [
    {
      title: '所属用户',
      dataIndex: 'ownerId',
      align: 'center',
      hideInForm: true,
      hideInTable: currUser?.role !== Role.ADMIN,
      hideInSearch: currUser?.role !== Role.ADMIN,
      fieldProps: { showSearch: true },
      debounceTime: 300,
      request: (val) => queryCompanies(val.keyWords),
      width: 150,
    },
    {
      title: '路段名称',
      dataIndex: 'parkingLotId',
      hideInForm: true,
      align: 'center',
      render: (_, record) => record.parkingLotName,
      fieldProps: { showSearch: true },
      debounceTime: 300,
      request: (val) => queryParkinglotNames(val.keyWords),
    },
    {
      title: '泊位编号',
      dataIndex: 'spotId',
      hideInForm: true,
      align: 'center',
    },
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      hideInForm: true,
      align: 'center',
      valueEnum: {
        0: { text: '地磁' },
        1: { text: '巡检车' },
        99: { text: '其他' },
      },
    },
    {
      title: '故障类型',
      dataIndex: 'failureType',
      hideInForm: true,
      align: 'center',
      valueEnum: {
        0: { text: '有车显示无车' },
        1: { text: '无车显示有车' },
        2: { text: '车牌识别错误' },
        3: { text: '地磁损坏' },
      },
    },
    {
      title: '上报时间',
      dataIndex: 'reportTime',
      hideInForm: true,
      hideInSearch: true,
      align: 'center',
      valueType: 'dateTime',
    },
    {
      title: '上报人姓名',
      dataIndex: 'reporterName',
      hideInForm: true,
      align: 'center',
    },
    {
      title: '上报人工号',
      dataIndex: 'reporterJobNo',
      hideInForm: true,
      align: 'center',
    },
    {
      title: '故障状态',
      dataIndex: 'status',
      hideInForm: true,
      hideInSearch: true,
      align: 'center',
      valueEnum: {
        0: { text: '待处理', status: 'processing' },
        1: { text: '已处理', status: 'success' },
      },
    },

    {
      title: '现场照片',
      dataIndex: 'photoUrl',
      hideInForm: true,
      hideInSearch: true,
      align: 'center',
      render: (_, record) => (
        <a
          onClick={() => {
            setImgUrl(record.photoUrl);
            setImgModalVisible(true);
          }}
        >
          查看图片
        </a>
      ),
    },
    {
      title: '故障描述',
      dataIndex: 'description',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '处理人',
      dataIndex: 'handler',
      hideInForm: true,
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '处理时间',
      dataIndex: 'handleTime',
      hideInForm: true,
      hideInSearch: true,
      align: 'center',
      valueType: 'dateTime',
    },
    {
      title: '处理结果',
      dataIndex: 'handleResult',
      hideInForm: true,
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '操作',
      width: 100,
      align: 'center',
      key: 'option',
      fixed: 'right',
      valueType: 'option',
      render: (_, record) =>
        ifModify
          ? [
              record.status == 0 ? (
                <a
                  key={`handle_${record._id}`}
                  onClick={() => {
                    setCurrId(record._id);
                    setUpVisible(true);
                  }}
                >
                  处理
                </a>
              ) : (
                <PlaceHolderCpn key={`handled_${record._id}`} text="已处理" />
              ),
            ]
          : [<PlaceHolderCpn key={`hd_${record._id}`} />],
    },
  ];

  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: '故障上报列表',
      }}
    >
      <ProTable<FailureReportTableItem>
        rowKey="_id"
        columns={columns}
        search={{ labelWidth: 'auto' }}
        scroll={{ x: true }}
        actionRef={actionRef}
        style={{ whiteSpace: 'nowrap' }}
        columnEmptyText="-"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        debounceTime={300}
        request={async (params, sort) => {
          return await queryFailureReportList(params, sort);
        }}
      />
      {imgModalVisible && imgUrl && (
        <ModalForm
          title="现场照片"
          visible={imgModalVisible}
          modalProps={{
            onCancel: () => {
              setImgModalVisible(false);
              setImgUrl('');
            },
          }}
          submitter={false}
        >
          <Image src={imgUrl} />
        </ModalForm>
      )}
      {upVisible && currId && (
        <HandleReport
          visible={upVisible}
          id={currId}
          setUnvisible={() => {
            setCurrId('');
            setUpVisible(false);
          }}
          reload={() => {
            actionRef.current?.reload();
          }}
        />
      )}
    </PageHeaderWrapper>
  );
};

export default FailureReportList;
